package com.ssy.lingxi.purchase.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageCustomRequest;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.purchase.api.common.OrderConstant;
import com.ssy.lingxi.purchase.api.dto.request.purchase.DemandMemberRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryAddRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryListRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryProductRequest;
import com.ssy.lingxi.purchase.api.dto.response.CountryAreaResponse;
import com.ssy.lingxi.purchase.api.dto.response.LogStateResponse;
import com.ssy.lingxi.purchase.api.dto.response.online.CountryArea;
import com.ssy.lingxi.purchase.api.dto.response.purchase.DemandMemberResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.ExternalPurchaseInquiryLogResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.InteriorPurchaseInquiryLogResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.PurchaseInquiryListResponse;
import com.ssy.lingxi.purchase.api.enums.purchase.*;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.*;
import com.ssy.lingxi.purchase.entity.quotedprice.InteriorConfirmQuotedPriceLog;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPrice;
import com.ssy.lingxi.purchase.repository.*;
import com.ssy.lingxi.purchase.utils.PurchaseUtils;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.ExternalProcessWithRolesQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.InternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskStartVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购需求单业务基础类
 *
 * @author wrc
 * @date 2021/1/19
 */


@Slf4j
@Component
public abstract class BasePurchaseInquiry {
    @Resource
    PurchaseInquiryRepository purchaseInquiryRepository;
    @Resource
    ProcessFeign taskExecuteControllerFeign;
    @Resource
    ExternalPurchaseInquiryLogRepository externalLogRepository;
    @Resource
    InteriorPurchaseInquiryLogRepository interiorPurchaseInquiryLogRepository;
    @Resource
    DemandMemberRepository demandMemberRepository;
    @Resource
    ReportControllerFeign reportControllerFeign;
    @Resource
    SystemMessageControllerFeign systemMessageControllerFeign;
    @Resource
    QuotedPriceRepository quotedPriceRepository;
    @Resource
    InteriorConfirmQuotedPriceLogRepository interiorConfirmQuotedPriceLogRepository;

    /**
     * 根据不同类型查询采购询价单列表 queryType：
     */
    public Wrapper<PageData<PurchaseInquiryListResponse>> getQuery(UserLoginCacheDTO sysUser, PurchaseInquiryListRequest request, Integer queryType) {
        List<PurchaseInquiryListResponse> responses = new ArrayList<>();
        Specification<PurchaseInquiry> purchaseInquiryQuery = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            List<Predicate> list = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("createMemberId").as(Long.class), sysUser.getMemberId()));
            predicates.add(criteriaBuilder.equal(root.get("createMemberRoleId").as(Long.class), sysUser.getMemberRoleId()));
            if (StringUtils.hasLength(request.getMemberName()))
                predicates.add(criteriaBuilder.like(root.get("memberName"), "%" + request.getMemberName() + "%"));
            if (null != request.getStartTime()) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), request.getStartTime()));
            }
            if (null != request.getEndTime()) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), request.getEndTime()));
            }
            if (StringUtils.hasLength(request.getDetails())) {
                predicates.add(criteriaBuilder.like(root.get("details"), "%" + request.getDetails() + "%"));
            }
            if (StringUtils.hasLength(request.getPurchaseInquiryNo())) {
                predicates.add(criteriaBuilder.like(root.get("purchaseInquiryNo"), "%" + request.getPurchaseInquiryNo() + "%"));
            }
            if (PurchaseInquiryListEnum.PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                if (null != request.getExternalState()) {
                    predicates.add(criteriaBuilder.equal(root.get("externalState"), request.getExternalState()));
                }
                if (null != request.getInteriorState()) {
                    if (request.getInteriorState() < PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState()) {
                        predicates.add(criteriaBuilder.equal(root.get("interiorState"), request.getInteriorState()));
                    } else {
                        predicates.add(criteriaBuilder.equal(root.get("confirmInteriorState"), request.getInteriorState()));
                    }

                }
            } else if (PurchaseInquiryListEnum.ADD_PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("shopType"),request.getShopType()));

                predicates.add(criteriaBuilder.or(root.get("interiorState").in(Arrays.asList(
                        PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT.getState(), PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT1.
                                getState(),PurchaseInquiryListInteriorWorkStateEnum.SUBMIT_NOT_ADOPT2.getState())),
                        criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.AUDIT_NOT_REQUIREMENTS.getState())));
            }else if (PurchaseInquiryListEnum.EXAMINE_PURCHASE_INQUIRY_LIST1.getType().equals(queryType)) {
                    predicates.add(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_REQUIREMENTS.getState()));
                    predicates.add(criteriaBuilder.equal(root.get("interiorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE1.getState()));
            } else if (PurchaseInquiryListEnum.EXAMINE_PURCHASE_INQUIRY_LIST2.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE2.getState()));
            } else if (PurchaseInquiryListEnum.SUBMIT_PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_SUBMIT_OFFER.getState()));
            } else if (PurchaseInquiryListEnum.CONFIRM_QUOTED_PRICE_LIST.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState()),
                               criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState()),
                               criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.COMPLETE.getState())));
            }
            Predicate[] predicate = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(predicate));
        };
        Page<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAll(purchaseInquiryQuery, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (0 < purchaseInquirys.getTotalElements()) {
            responses = purchaseInquirys.getContent().stream().map(temp -> {
                PurchaseInquiryListResponse response = new PurchaseInquiryListResponse();
                response.setCreateTime(temp.getCreateTime());
                response.setDeliveryTime(temp.getDeliveryTime());
                response.setPurchaseInquiryNo(temp.getPurchaseInquiryNo());
                response.setOfferEndTime(temp.getOfferEndTime());
                response.setId(temp.getId());
                response.setMemberRoleId(temp.getMemberRoleId());
                response.setMemberName(temp.getMemberName());
                response.setMemberId(temp.getMemberId());
                response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(temp.getConfirmInteriorState() != null ? temp.getConfirmInteriorState() : temp.getInteriorState()));
                response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(temp.getExternalState()));
                response.setInteriorState(temp.getInteriorState());
                response.setExternalState(temp.getExternalState());
                response.setDetails(temp.getDetails());
                response.setCreateTime(temp.getCreateTime());
                response.setTurn(temp.getTurn());
                response.setCount(temp.getCount());
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(purchaseInquirys.getTotalElements(),responses));
    }


    /**
     * 初始化采购询价单详情
     */
    public PurchaseInquiry initPurchaseInquiry(PurchaseInquiryAddRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = new PurchaseInquiry();
        purchaseInquiry.setMemberName(request.getMemberName());
        purchaseInquiry.setType(request.getType());
        purchaseInquiry.setTaxes(request.getTaxes());
        purchaseInquiry.setPurchaseType(request.getPurchaseType());
        purchaseInquiry.setPurchaseInquiryNo(PurchaseUtils.randomUniqueNumber("XJ"));
        purchaseInquiry.setTurn(1);
        purchaseInquiry.setPriceContrast(request.getPriceContrast());
        purchaseInquiry.setPaymentType(request.getPaymentType());
        purchaseInquiry.setPackRequire(request.getPackRequire());
        purchaseInquiry.setOtherRequire(request.getOtherRequire());
        purchaseInquiry.setOfferEndTime(request.getOfferEndTime());
        purchaseInquiry.setMemberRoleId(request.getMemberRoleId());
        purchaseInquiry.setMemberId(request.getMemberId());
        purchaseInquiry.setAddress(request.getAddress());
        purchaseInquiry.setLogistics(request.getLogistics());
        purchaseInquiry.setDetails(request.getDetails());
        purchaseInquiry.setDeliveryTime(request.getDeliveryTime());
        purchaseInquiry.setCreateTime(request.getDeliveryTime());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        purchaseInquiry.setCreateMemberId(sysUser.getMemberId());
        purchaseInquiry.setCreateMemberRoleId(sysUser.getMemberRoleId());
        purchaseInquiry.setCreateMemberName(sysUser.getCompany());
        purchaseInquiry.setIsAreas(OrderConstant.State.STOP);
        purchaseInquiry.setShopIds(request.getShopIds());
        purchaseInquiry.setShopType(request.getShopType());
        List<CountryAreaResponse> areas = request.getAreas();
        if (!CollectionUtils.isEmpty(areas)) {
            purchaseInquiry.setIsAreas(OrderConstant.State.START);
            List<CountryArea> countryAreas = areas.stream().map(temp -> {
                CountryArea area = new CountryArea();
                area.setCity(temp.getCity());
                area.setProvinceCode(temp.getProvinceCode());
                area.setCityCode(temp.getCityCode());
                area.setProvince(temp.getProvince());
                return area;
            }).collect(Collectors.toList());
            purchaseInquiry.setAreas(countryAreas);
        }
        purchaseInquiry.setCreateTime(System.currentTimeMillis());
        purchaseInquiry.setAddressId(request.getAddressId());
        purchaseInquiry.setMaterielMode(request.getMaterielMode());
        purchaseInquiry.setTransactionUurls(request.getTransactionUurls());
        return purchaseInquiry;
    }



    /**
     *初始化采购需求单物料信息列表
     */
    public  List<PurchaseInquiryProduct> initPurchaseInquiryProduct(List<PurchaseInquiryProductRequest> materiels, Long id){
        return materiels.stream().map(temp -> {
            PurchaseInquiryProduct purchaseInquiryProduct = new PurchaseInquiryProduct();
            purchaseInquiryProduct.setCategory(temp.getCategory());
            purchaseInquiryProduct.setIds(temp.getIds());
            purchaseInquiryProduct.setCategoryId(temp.getCategoryId());
            purchaseInquiryProduct.setMemberCategoryId(temp.getMemberCategoryId());
            purchaseInquiryProduct.setUrls(temp.getUrls());
            purchaseInquiryProduct.setUnit(temp.getUnit());
            purchaseInquiryProduct.setPurchaseInquiryId(id);
            purchaseInquiryProduct.setNumber(temp.getNumber());
            purchaseInquiryProduct.setPurchaseCount(temp.getPurchaseCount());
            purchaseInquiryProduct.setName(temp.getName());
            purchaseInquiryProduct.setModel(temp.getModel());
            purchaseInquiryProduct.setBrand(temp.getBrand());
            purchaseInquiryProduct.setItemNo(temp.getItemNo());
            purchaseInquiryProduct.setGoodsId(temp.getGoodsId());
            purchaseInquiryProduct.setProductAttributeJson(temp.getProductAttributeJson());
            purchaseInquiryProduct.setGoodsGroup(temp.getGoodsGroup());
            return purchaseInquiryProduct;
        }).collect(Collectors.toList());
    }


    /**
     * 初始化需求对接会员列表信息
     */
    public List<DemandMember> initDemandMember(List<DemandMemberRequest> demandMembers, Integer type, Long id) {
        return demandMembers.stream().map(temp -> {
            DemandMember dm = new DemandMember();
            dm.setLevelTag(org.apache.commons.lang3.StringUtils.isBlank(temp.getLevelTag()) ? "" : temp.getLevelTag());
            dm.setType(type);
//            dm.setIsSubMember(temp.getIsSubMember());
//            dm.setState(temp.getState());
            dm.setRoleName(temp.getRoleName());
            dm.setRoleId(temp.getRoleId());
            dm.setPurchaseInquiryId(id);
            dm.setMemberTypeName(temp.getMemberTypeName());
//            dm.setMembershipOrNot(temp.getMembershipOrNot());
            dm.setMemberName(temp.getMemberName());
            dm.setMemberId(temp.getMemberId());
            return dm;
        }).collect(Collectors.toList());
    }

    /**
    * 启动工作流
    */
    public  Wrapper<SimpleTaskCompleteVO> startWork(UserLoginCacheDTO sysUser, Long id, Integer processEnum){
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setProcessKey(ProcessEnum.getProcessKeyByCode(processEnum));
        processStartVO.setDataId(id);
        return taskExecuteControllerFeign.startSimpleProcess(processStartVO);
    }

    /**
     * 执行工作流
     */
    public Wrapper<SimpleTaskCompleteVO> executeWork(Long memberId, Long memberRoleId, Long id, Integer processEnum, Integer step, String taskId, Integer agree) {
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setMemberId(memberId);
        processStartVO.setRoleId(memberRoleId);
        processStartVO.setProcessKey(ProcessEnum.getProcessKeyByCode(processEnum));
        processStartVO.setAgree(agree);
        processStartVO.setTaskId(taskId);
        processStartVO.setDataId(id);
        return taskExecuteControllerFeign.completeSimpleTask(processStartVO);
    }


    /**
     * 查询采购需求单外部操作记录
     */
    public List<InteriorPurchaseInquiryLogResponse> getInteriorLog(Long purchaseInquiryId) {
        List<InteriorPurchaseInquiryLog> interiorLogs = interiorPurchaseInquiryLogRepository.findAllByPurchaseInquiryId(purchaseInquiryId);
        if (CollectionUtils.isEmpty(interiorLogs)) {
            return new ArrayList<>();
        }
        //查询采购商确认报价日志
        List<InteriorConfirmQuotedPriceLog> confirmQuotedPriceLogs = interiorConfirmQuotedPriceLogRepository.findAllByPurchaseInquiryId(purchaseInquiryId);
        if (!CollectionUtils.isEmpty(confirmQuotedPriceLogs)) {
            List<InteriorPurchaseInquiryLog> list = confirmQuotedPriceLogs.stream().map(i -> BeanUtil.copyProperties(i, InteriorPurchaseInquiryLog.class)).collect(Collectors.toList());
            interiorLogs.addAll(list);
        }

        return interiorLogs.stream().sorted(Comparator.comparingLong(InteriorPurchaseInquiryLog::getStep)).map(temp -> {
            InteriorPurchaseInquiryLogResponse logResponse = new InteriorPurchaseInquiryLogResponse();
            BeanUtils.copyProperties(temp, logResponse);
            logResponse.setRoleName(temp.getRoleName());
            logResponse.setDepartment(temp.getDepartment());
            logResponse.setStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(temp.getState()));
            logResponse.setOperation(PurchaseInquiryInternalOperationRecordEnum.getName(temp.getOperation()));
            logResponse.setAuditOpinion(StatusEnum.AGREE.getCHName().equals(temp.getAuditOpinion())? StatusEnum.getName(temp.getAuditOpinion()) : temp.getAuditOpinion());
            return logResponse;
        }).collect(Collectors.toList());
    }


    /**
    * 查询采购需求单外部操作记录
    */
    public  List<ExternalPurchaseInquiryLogResponse> getExternalLog(Long purchaseInquiryId){
        List<ExternalPurchaseInquiryLog> externalLogs = externalLogRepository.findAllByPurchaseInquiryId(purchaseInquiryId);
        if(CollectionUtils.isEmpty(externalLogs)){
            return new ArrayList<>();
        }
        return  externalLogs.stream().map(temp->{
            ExternalPurchaseInquiryLogResponse logResponse=new   ExternalPurchaseInquiryLogResponse();
            BeanUtils.copyProperties(temp,logResponse);
            logResponse.setStateName(PurchaseInquiryListExternalWorkStateEnum.getName(temp.getState()));
            logResponse.setAuditOpinion(StatusEnum.AGREE.getCHName().equals(temp.getAuditOpinion())? StatusEnum.getName(temp.getAuditOpinion()) : temp.getAuditOpinion());
            logResponse.setOperation(PurchaseInquiryExternalOperationRecordEnum.getName(temp.getOperation()));
            return logResponse;
        }).collect(Collectors.toList());
    }


    /**
     * 查询采购需求单流转状态 外部
     */
    public  List<LogStateResponse> getLogStateResponse(Integer processEnum, Integer step,List<Long> roleIds,Long subRoleId){
        ExternalProcessWithRolesQueryVO taskParamQueryVO = new ExternalProcessWithRolesQueryVO();
        taskParamQueryVO.setProcessKey(ProcessEnum.getProcessKeyByCode(processEnum));
        taskParamQueryVO.setRoleIds(roleIds);
        taskParamQueryVO.setSubRoleIds(Collections.singletonList(subRoleId));
        Wrapper<SimpleProcessDefVO> listWrapper = taskExecuteControllerFeign.findSimpleExternalTaskDefinitions(taskParamQueryVO);
        if(ResponseCode.SUCCESS.getCode()!=listWrapper.getCode()){
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        return data.stream().map(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            quotationState.setIsExecute((null!=step&&step>=taskStepQueryVO.getTaskStep())? OrderConstant.State.START : OrderConstant.State.STOP);
            quotationState.setState(taskStepQueryVO.getTaskStep());
            quotationState.setStateName(PurchaseInquiryListExternalWorkStateEnum.getName(taskStepQueryVO.getTaskStep()));
            return quotationState;
        }).collect(Collectors.toList());
    }

    /**
     * 查询采购需求单流转状态 内部
     */
    public  List<LogStateResponse> getLogStateInterior(Long memberId, Integer processEnum, Integer nextStep){
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        if(memberId != null) {
            taskParamQueryVO.setMemberId(memberId);
        }
        taskParamQueryVO.setProcessKey(ProcessEnum.getProcessKeyByCode(processEnum));
        Wrapper<SimpleProcessDefVO> listWrapper = taskExecuteControllerFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        if(ResponseCode.SUCCESS.getCode()!=listWrapper.getCode()){
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        return data.stream().map(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            quotationState.setIsExecute((null!=nextStep&&nextStep>=taskStepQueryVO.getTaskStep())? OrderConstant.State.START : OrderConstant.State.STOP);
            quotationState.setState(taskStepQueryVO.getTaskStep());
            quotationState.setStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(taskStepQueryVO.getTaskStep()));
            return quotationState;
        }).collect(Collectors.toList());
    }

    /**
     * 查询采购需求单流转状态 内部
     */
    public  List<LogStateResponse> logStateInterior(Long memberId, Integer processEnum, Integer nextStep){
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        taskParamQueryVO.setProcessKey(ProcessEnum.getProcessKeyByCode(processEnum));
        if(memberId != null) {
            taskParamQueryVO.setMemberId(memberId);
        }
        Wrapper<SimpleProcessDefVO> listWrapper = taskExecuteControllerFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        if(ResponseCode.SUCCESS.getCode()!=listWrapper.getCode()){
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        return data.stream().map(taskStepQueryVO -> {
            LogStateResponse quotationState = new LogStateResponse();
            quotationState.setOperationalProcess(taskStepQueryVO.getTaskName());
            quotationState.setRoleName(taskStepQueryVO.getRoleName());
            quotationState.setIsExecute((null!=nextStep&&nextStep>=taskStepQueryVO.getTaskStep())? OrderConstant.State.START : OrderConstant.State.STOP);
            quotationState.setState(taskStepQueryVO.getTaskStep());
            quotationState.setStateName(QuotedPriceInteriorWorkStateEnum.getName(taskStepQueryVO.getTaskStep()));
            return quotationState;
        }).collect(Collectors.toList());
    }


    /**
     * 记录采购询价单外部操作记录
     */
    public void saveExternalLog(UserLoginCacheDTO sysUser, String operation, Integer state, Long id, String auditOpinion) {
        //记录操作记录
        ExternalPurchaseInquiryLog externalLog = new ExternalPurchaseInquiryLog();
        externalLog.setRoleName(sysUser.getMemberRoleName());
        externalLog.setPurchaseInquiryId(id);
        externalLog.setState(state);
        externalLog.setOperation(operation);
        externalLog.setAuditOpinion(auditOpinion);
        externalLog.setCreateTime(System.currentTimeMillis());
        externalLog.setCreateMemberId(sysUser.getMemberId());
        externalLog.setCreateMemberRoleId(sysUser.getMemberRoleId());
        externalLogRepository.saveAndFlush(externalLog);
    }

    /**
     * 记录采购询价单内部操作记录
     */
    public void saveInteriorConfirmQuotedPriceLog(UserLoginCacheDTO sysUser, String operation, Integer step, Integer state, Long id, String auditOpinion) {
        InteriorConfirmQuotedPriceLog priceLog = interiorConfirmQuotedPriceLogRepository.findByStepAndPurchaseInquiryId(PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState(),id);//判断是否已经存在待比价步骤
        if (!(PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState().equals(step) && priceLog != null)) {
            //操作记录
            InteriorConfirmQuotedPriceLog interiorLog = new InteriorConfirmQuotedPriceLog();
            interiorLog.setRoleName(sysUser.getUserName());
            interiorLog.setDepartment(sysUser.getUserOrgName());
            interiorLog.setPosition(sysUser.getUserJobTitle());
            interiorLog.setPurchaseInquiryId(id);
            interiorLog.setState(state);
            interiorLog.setStep(step);
            interiorLog.setOperation(operation);
            interiorLog.setAuditOpinion(auditOpinion);
            interiorLog.setCreateTime(System.currentTimeMillis());
            interiorLog.setCreateRoleId(sysUser.getMemberRoleId());
            interiorLog.setCreateMemberId(sysUser.getMemberId());
            interiorConfirmQuotedPriceLogRepository.saveAndFlush(interiorLog);
        }

    }

    /**
     * 根据需求单ID查询需求对接会员列表
     */
    public List<DemandMemberResponse> getDemandMembers(Long purchaseInquiryId) {
        List<DemandMember> demandMembers = demandMemberRepository.findAllByPurchaseInquiryId(purchaseInquiryId);
        if (CollectionUtils.isEmpty(demandMembers)) {
            return new ArrayList<>();
        }
        return demandMembers.stream().map(temp -> {
            DemandMemberResponse response = new DemandMemberResponse();
            BeanUtils.copyProperties(temp, response);
            response.setIsSubMember(temp.getIsSubMember());
            response.setMembershipOrNot(temp.getMembershipOrNot());

            return response;
        }).collect(Collectors.toList());
    }


    /**
     * 增加扣减记录操作数据记录
     */
    @Async
    public void reduceCount(String increaseTitle, Long memberId, Long memberRoleId, Integer dataSource, Long increaseCount, Integer increaseOperateType, Long reduceCount, Integer reduceOperateType) {
        OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
        operateNoticeVO.setDataSource(dataSource);
        operateNoticeVO.setMemberId(memberId);
        operateNoticeVO.setRoleId(memberRoleId);
        operateNoticeVO.setReduceCount(reduceCount);
        operateNoticeVO.setIncreaseTitle(increaseTitle);
        operateNoticeVO.setReduceOperateType(reduceOperateType);
        operateNoticeVO.setIncreaseCount(increaseCount);
        operateNoticeVO.setIncreaseOperateType(increaseOperateType);
        reportControllerFeign.addOperateNotice(operateNoticeVO);
    }

    /**
     * 发消息
     */
    @Async
    public void sendSystemMessagePurchaseInquiry(PurchaseInquiry purchaseInquiry, String name) {
        SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
        systemMessageRequest.setMemberId(purchaseInquiry.getCreateMemberId());
        systemMessageRequest.setRoleId(purchaseInquiry.getCreateMemberRoleId());
        systemMessageRequest.setMessageNotice(name);
        systemMessageRequest.setParams(Arrays.asList(purchaseInquiry.getPurchaseInquiryNo(), purchaseInquiry.getDetails()));
        systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
    }

    /**
     * 发自定义消息
     */
    @Async
    public void sendSystemMessagePurchaseInquiryCustom(QuotedPrice quotedPrice, String title, String content) {
        SystemMessageCustomRequest systemMessageCustomRequest = new SystemMessageCustomRequest();
        systemMessageCustomRequest.setMemberId(quotedPrice.getCreateMemberId());
        systemMessageCustomRequest.setRoleId(quotedPrice.getCreateMemberRoleId());
        systemMessageCustomRequest.setTitle(title);
        systemMessageCustomRequest.setContent(content);
        systemMessageControllerFeign.sendCustomMessage(systemMessageCustomRequest);
    }

    /**
     * 查询条件
     */
    public void queryCondition(String memberName, Long startTime, Long endTime, String details, String purchaseInquiryNo, List<Predicate> predicates, CriteriaBuilder criteriaBuilder, Root root) {
        if (StringUtils.hasLength(memberName)) {
            predicates.add(criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%"));
        }
        if (null != startTime) {
            predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), startTime));
        }
        if (null != endTime) {
            predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), endTime));
        }
        if (StringUtils.hasLength(details)) {
            predicates.add(criteriaBuilder.like(root.get("details"), "%" + details + "%"));
        }
        if (StringUtils.hasLength(purchaseInquiryNo)) {
            predicates.add(criteriaBuilder.like(root.get("purchaseInquiryNo"), "%" + purchaseInquiryNo + "%"));
        }
    }

    public List<Long> getRolesByPurchaseInquiry(Long inquiryId) {
        List<QuotedPrice> quotedPriceList = quotedPriceRepository.findAllByPurchaseInquiryId(inquiryId);
        if (CollectionUtil.isNotEmpty(quotedPriceList)) {
            return quotedPriceList.stream().map(QuotedPrice::getCreateMemberRoleId).collect(Collectors.toList());
        }
        return null;
    }
}
